class Topic
  include Mongoid::Document
  include Mongoid::Timestamps::Created
  include Mongoid::Timestamps::Updated

  field :title, type: String
  # field :next_index, type: Integer, default: 0

  belongs_to :author, class_name: "User", inverse_of: :topics
  
  # belongs_to :competition
  # belongs_to :question_list
  # belongs_to :question
  # belongs_to :task
  belongs_to :topic_container, polymorphic: true

  has_many :remarks, order: :position.asc, dependent: :destroy

  has_and_belongs_to_many :tags, inverse_of: nil

  def last_remark
    self.remarks.sort.last
  end

  def competition
    self.topic_container.is_a?(Competition) ?
      self.topic_container : 
      nil
  end
  def question_list
    self.topic_container.is_a?(QuestionList) ?
      self.topic_container : 
      nil
  end
  def question
    self.topic_container.is_a?(Question) ?
      self.topic_container : 
      nil
  end
  def task
    self.topic_container.is_a?(Task) ?
      self.topic_container : 
      nil
  end
  def competition_id
    self.topic_container
  end
  def question_list_id
    self.topic_container
  end
  def question_id
    self.topic_container
  end
  def task_id
    self.topic_container
  end

  #def set_position(remark, save)
  #  remark.position = self.next_index
  #  if save
  #    self.next_index = self.next_index + 1
  #    self.save
  #  end
  #end

  def get_top_object
    if self.topic_container.is_a?(Competition)
      self
    else
      self.topic_container
    end
  end

  def get_competition
    if self.topic_container.is_a?(Competition)
      self.topic_container
    elsif self.topic_container.is_a?(Question)
      self.topic_container.question_list.competition
    else
      self.topic_container.competition
    end
  end

  def get_question_list
    if self.topic_container.is_a?(QuestionList)
      self.question_list
    elsif self.topic_container.is_a?(Question)
      self.question.question_list
    else
      nil
    end
  end

  def belongs_to_question_list?
    self.topic_container.is_a? QuestionList
  end
  def belongs_to_question?
    self.topic_container.is_a? Question
  end

  def belongs_to_task?
    self.topic_container.is_a? Task
  end

  # tag is a String
  def append_tag(tag)
    return if Tag.where( :_id.in => self.tag_ids, name: tag ).exists?
    t = Tag.find_or_create_by(name: tag)
    return if !t.scope_name.nil?
    self.tags << t
    self.save
  end

  before_create do |doc|
    doc.topic_container # to make sure topic_container is properly set
  end
end
